package com.codeworker.app.ui.property;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;
import androidx.appcompat.widget.Toolbar;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.codeworker.app.R;
import com.codeworker.app.data.entity.Property;
import com.codeworker.app.data.model.PropertyModel;
import com.codeworker.app.databinding.FragmentPropertyBinding;
import com.codeworker.app.ui.AppSettingActivity;
import com.codeworker.app.ui.wrapper.MyDecoration;
import com.codeworker.app.ui.wrapper.MyPopupWindow;
import com.codeworker.app.ui.wrapper.MyPopupWindowAdapter;
import com.codeworker.app.utils.FormatUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.function.Predicate;
import java.util.stream.Collectors;

public class PropertyFragment extends Fragment {

    private PropertyModel propertyModel;
    private FragmentPropertyBinding binding;
    private static final int ADD_PROPERTY_ACTIVITY_REQUEST_CODE = 1;
    private static final int REPAY_PROPERTY_ACTIVITY_REQUEST_CODE = 2;
    private TextView tvHeaderValue1;
    private TextView tvHeaderValue2;
    private TextView tvHeaderValue3;

    @SuppressLint("SetTextI18n")
    @RequiresApi(api = Build.VERSION_CODES.N)
    public View onCreateView(@NonNull LayoutInflater inflater,
                             ViewGroup container, Bundle savedInstanceState) {
        binding = FragmentPropertyBinding.inflate(inflater, container, false);
        View root = binding.getRoot();

        //自定义toolbar和菜单
        setHasOptionsMenu(true);
        Toolbar toolbar = root.findViewById(R.id.toolbar);
        TextView tvToolbarTitle = root.findViewById(R.id.tv_toolbar_title);
        //去除toolbar默认的title，设置tv的title
        toolbar.setTitle("");
        tvToolbarTitle.setText(R.string.title_property);
        toolbar.setNavigationIcon(null);
        ((AppCompatActivity) requireActivity()).setSupportActionBar(toolbar);

        RecyclerView recyclerView = root.findViewById(R.id.recyclerview);
        final PropertyListAdapter adapter = new PropertyListAdapter(new PropertyListAdapter.ItemDiff());
        recyclerView.addItemDecoration(new MyDecoration());
        recyclerView.setAdapter(adapter);
        recyclerView.setLayoutManager(new LinearLayoutManager(getContext()));

        propertyModel = new ViewModelProvider(this).get(PropertyModel.class);
        propertyModel.getPropertyListLiveData().observe(getViewLifecycleOwner(), list -> {
            adapter.submitList(list);
            setHeaderData(list);
        });
        initHeader(root, propertyModel.getPropertyList());
        tvHeaderValue1.setOnClickListener(view ->
                propertyModel.getPropertyListLiveData().observe(getViewLifecycleOwner(), adapter::submitList));
        tvHeaderValue2.setOnClickListener(tvHeaderClickEvent(adapter, v -> v.getValue() >= 0));
        tvHeaderValue3.setOnClickListener(tvHeaderClickEvent(adapter, v -> v.getValue() <= 0));
        return root;
    }

    private View.OnClickListener tvHeaderClickEvent(PropertyListAdapter adapter, Predicate<Property> predicate) {
        return view -> propertyModel.getPropertyListLiveData().observe(getViewLifecycleOwner(), list -> {
            List<Property> copyList = list.stream().filter(predicate).collect(Collectors.toList());
            adapter.submitList(copyList);
        });
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    private void initHeader(View root, List<Property> list) {
        TextView tvHeader1 = root.findViewById(R.id.tv_header_title1);
        TextView tvHeader2 = root.findViewById(R.id.tv_header_title2);
        TextView tvHeader3 = root.findViewById(R.id.tv_header_title3);
        tvHeaderValue1 = root.findViewById(R.id.tv_header_value1);
        tvHeaderValue2 = root.findViewById(R.id.tv_header_value2);
        tvHeaderValue3 = root.findViewById(R.id.tv_header_value3);
        TextView tv = root.findViewById(R.id.text);
        tvHeader1.setText("净资产");
        tvHeader1.setCompoundDrawables(null, null, null, null);
        tvHeader2.setText("总资产");
        tvHeader3.setText("负债");
        tv.setText("资产明细");
        setHeaderData(list);
    }

    private void setHeaderData(List<Property> list) {
        int total = 0;
        int debt = 0;
        for (Property property : list) {
            int dataValue = property.getValue();
            if (dataValue > 0) {
                total += dataValue;
            } else {
                debt += dataValue;
            }
        }
        int balance = total + debt;
        tvHeaderValue1.setText(FormatUtil.format2(balance * 1.0 / 100));
        tvHeaderValue2.setText(String.valueOf(total / 100));
        tvHeaderValue3.setText(String.valueOf(debt / 100));
    }

    @Override
    public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater) {
        inflater.inflate(R.menu.toolbar_property_menu, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @SuppressLint("NonConstantResourceId")
    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()) {
            case R.id.action_bar_add_property: {
                Intent intent = new Intent(getContext(), AddPropertyActivity.class);
                startActivityForResult(intent, ADD_PROPERTY_ACTIVITY_REQUEST_CODE);
                return true;
            }
            case R.id.action_bar_remove_property: {
                popupWindowToDeleteProperty(requireView());
                return true;
            }
            case R.id.action_bar_repay_property: {
                Intent intent = new Intent(getContext(), RepayPropertyActivity.class);
                startActivityForResult(intent, REPAY_PROPERTY_ACTIVITY_REQUEST_CODE);
                return true;
            }
            case R.id.action_bar_app_setting: {
                Intent intent = new Intent(getContext(), AppSettingActivity.class);
                startActivity(intent);
                return true;
            }
            default:
                return super.onOptionsItemSelected(item);
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == Activity.RESULT_CANCELED) return;

        if (resultCode != Activity.RESULT_OK) {
            Toast.makeText(getContext(), R.string.toast_unknown_error, Toast.LENGTH_SHORT).show();
            return;
        }

        switch (requestCode) {
            case ADD_PROPERTY_ACTIVITY_REQUEST_CODE:
                Property property = (Property) data.getExtras().getSerializable(AddPropertyActivity.EXTRA_REPLY);
                propertyModel.insert(property);
                break;
            case REPAY_PROPERTY_ACTIVITY_REQUEST_CODE:
                propertyModel.repay(
                        data.getExtras().getInt(RepayPropertyActivity.EXTRA_REPLY_INPUT),
                        data.getExtras().getInt(RepayPropertyActivity.EXTRA_REPLY_OUTPUT),
                        data.getExtras().getInt(RepayPropertyActivity.EXTRA_REPLY_MONEY)
                );
                break;
            default:
                Toast.makeText(getContext(), "R.string.empty_not_saved", Toast.LENGTH_SHORT).show();
        }
    }

    //设置弹窗事件
    @RequiresApi(api = Build.VERSION_CODES.N)
    private void popupWindowToDeleteProperty(View v) {
        @SuppressLint("InflateParams") View popUpView
                = LayoutInflater.from(v.getContext()).inflate(R.layout.layout_common_popup, null);
        //设置适配器的数据项
        ListView listView = popUpView.findViewById(R.id.lv_common_popup);
        List<MyPopupWindowAdapter.PopupWindowViewHolderInDB> popupWindowItems = new ArrayList<>();
        List<Property> properties = Objects.requireNonNull(propertyModel.getPropertyListLiveData().getValue());
        for (Property property : properties) {
            popupWindowItems.add(new MyPopupWindowAdapter.PopupWindowViewHolderInDB(property.getName(), property.getId()));
        }

        //初始化适配器
        MyPopupWindowAdapter adapter = new MyPopupWindowAdapter(v.getContext(), popupWindowItems);
        listView.setAdapter(adapter);

        //设置弹窗
        boolean isFixedPopupWindowHeight = popupWindowItems.size() > MyPopupWindow.MAX_POPUP_WINDOW_ITEMS_SIZE;
        MyPopupWindow myPopupWindow = new MyPopupWindow(popUpView, this.requireActivity(), isFixedPopupWindowHeight);

        //弹出创建显示在按钮下面
        myPopupWindow.showAtLocation(v, Gravity.BOTTOM, 0, 0);
        listView.setOnItemClickListener((parent, view, position, id) -> {
            if (popupWindowItems.get(position).getId() == 1) {
                Toast.makeText(getContext(), R.string.toast_can_not_delete, Toast.LENGTH_SHORT).show();
                return;
            }
            //关闭弹出框
            myPopupWindow.dismiss();
            propertyModel.softDelete(popupWindowItems.get(position).getId());
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        binding = null;
    }
}